package com.we823.project.controller.manage;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.we823.project.controller.AbstractBaseController;
import com.we823.project.core.web.WebConstants;
import com.we823.project.model.RoleModel;
import com.we823.project.model.we.PermissionModel;
import com.we823.project.model.we.ResourceModel;
import com.we823.project.model.we.RoleResourceModel;
import com.we823.project.model.we.RoleResourcePermissionModel;
import com.we823.project.repository.service.sys.RoleService;
import com.we823.project.repository.service.we.PermissionService;
import com.we823.project.repository.service.we.ResourceService;
import com.we823.project.repository.service.we.RoleResourcePermissionService;
import com.we823.project.repository.service.we.RoleResourceService;
import com.we823.utils.web.RequestUtil;

@Controller
@RequestMapping(WebConstants.MANAGE_ROLE)
public class RoleController extends AbstractBaseController<RoleModel> {

	private String baseUrl = WebConstants.MANAGE_ROLE_TEMPLATE;

	@Autowired
	private RoleResourceService roleResourceService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RoleResourcePermissionService roleResourcePermissionService;

	private RoleService roleService;

	@Autowired
	public RoleController(RoleService roleService) {
		super(roleService);
		this.roleService = roleService;
		super.baseUrl = baseUrl;
		super.entityName = "role";
		setResourceIdentity("system:role");
	}

	@Override
	public Page<RoleModel> getData(PageRequest pageRequest,
			HttpServletRequest request, Model model, boolean pageable) {
		Page<RoleModel> rolePage = null;
		if (pageable) {
			rolePage = roleService.findAll(pageRequest);
		} else {
			rolePage = new PageImpl<>(roleService.findAll());
		}
		return rolePage;
	}

	@Override
	public String preAdd(HttpServletRequest request, Model model) {
		List<ResourceModel> resourceModels = resourceService
				.getListInMapByParentid(0);
		model.addAttribute("resources", resourceModels);
		
		List<PermissionModel> permissionModels=permissionService.findAll();
		model.addAttribute("permissions",permissionModels);

		return super.preAdd(request, model);
	}

	@Override
	public String preEdit(HttpServletRequest request, Model model) {
		String resultUrl = super.preEdit(request, model);
		
		List<ResourceModel> resourceModels = resourceService
				.getListInMapByParentid(0);
		model.addAttribute("resources", resourceModels);

		List<PermissionModel> permissionModels=permissionService.findAll();
		model.addAttribute("permissions",permissionModels);
		
		
		RoleModel roleModel = (RoleModel) model.asMap().get(entityName);

		if (roleModel != null) {
			int roleId = roleModel.getId();
			RoleResourceModel roleResourceModel = roleResourceService
					.findByRoleId(roleId);
			if (roleResourceModel != null) {
				String resourceIds = roleResourceModel.getResourceIds();
				model.addAttribute("resourceIds", resourceIds);
			}
		}
		return resultUrl;
	}

	@Override
	public String add(HttpServletRequest request, RoleModel entity,
			Model model, BindingResult bindingResult,RedirectAttributes redirectAttributes) {
		String result = super.add(request, entity, model, bindingResult,redirectAttributes);
		if (entity != null) {
			int roleId = entity.getId();
			String[] resourceIdList = RequestUtil.getValuesByParam(request,
					"resourceIds");
			/*
			String resourceIds = "";
			if(resourceIdList!=null) {
				resourceIds = StringUtils.join(resourceIdList, ",");
			}
			RoleResourceModel roleResourceModel = new RoleResourceModel();
			roleResourceModel.setResourceIds(resourceIds);
			roleResourceModel.setRoleId(roleId);

			roleResourceService.save(roleResourceModel);
			*/
			if(resourceIdList!=null && resourceIdList.length>0) {
				List<RoleResourcePermissionModel> roleResourcePermissionModels = new ArrayList<>();
				for (String resourceId : resourceIdList) {
					int rId=0;
					if(StringUtils.isNumeric(resourceId)) {
						rId = Integer.parseInt(resourceId);
						String[] permissionIdList = RequestUtil.getValuesByParam(request, "permission_"+resourceId);
						String permissionIds="";
						if(permissionIdList!=null) {
							permissionIds = StringUtils.join(permissionIdList,",");
						}
						
						RoleResourcePermissionModel roleResourcePermissionModel = new RoleResourcePermissionModel();
						roleResourcePermissionModel.setRoleid(roleId);
						roleResourcePermissionModel.setResourceid(rId);
						roleResourcePermissionModel.setPermissionIds(permissionIds);
						roleResourcePermissionModels.add(roleResourcePermissionModel);
					}
				}
				
				roleResourcePermissionService.save(roleResourcePermissionModels);
			}
		}
		return result;
	}

	@Override
	public String edit(HttpServletRequest request, Model model,
			RoleModel entity, BindingResult bindingResult,RedirectAttributes redirectAttributes) {
		String result = super.edit(request, model, entity, bindingResult,redirectAttributes);
		if(entity!=null) {
			int roleId = entity.getId();
			String[] resourceIdList = RequestUtil.getValuesByParam(request,
					"resourceIds");
			/*
			String resourceIds = "";
			if(resourceIdList!=null) {
				resourceIds = StringUtils.join(resourceIdList, ",");
			}
			RoleResourceModel roleResourceModel = roleResourceService.findByRoleId(roleId);
			if(roleResourceModel!=null) {
				
				roleResourceModel.setResourceIds(resourceIds);
				roleResourceService.save(roleResourceModel);
			}else {
				roleResourceModel = new RoleResourceModel();
				roleResourceModel.setResourceIds(resourceIds);
				roleResourceModel.setRoleId(roleId);

				roleResourceService.save(roleResourceModel);
			}*/
			if(roleId>0) {
				List<RoleResourcePermissionModel> oldRoleResourcePermissionModels = roleResourcePermissionService.findByRoleid(roleId);
				
				List<RoleResourcePermissionModel> needDeleteList = new ArrayList<>();
				List<RoleResourcePermissionModel> needUpdateList = new ArrayList<>();
				List<RoleResourcePermissionModel> needAddList = new ArrayList<>();
				
				if(resourceIdList!=null && resourceIdList.length>0) {
					List<RoleResourcePermissionModel> roleResourcePermissionModels = new ArrayList<>();
					for (String resourceId : resourceIdList) {
						int rId=0;
						if(StringUtils.isNumeric(resourceId)) {
							rId = Integer.parseInt(resourceId);
							String[] permissionIdList = RequestUtil.getValuesByParam(request, "permission_"+resourceId);
							String permissionIds="";
							if(permissionIdList!=null) {
								permissionIds = StringUtils.join(permissionIdList,",");
							}
							
							RoleResourcePermissionModel roleResourcePermissionModel = new RoleResourcePermissionModel();
							roleResourcePermissionModel.setRoleid(roleId);
							roleResourcePermissionModel.setResourceid(rId);
							roleResourcePermissionModel.setPermissionIds(permissionIds);
							roleResourcePermissionModels.add(roleResourcePermissionModel);
						}
					}
					
					if(oldRoleResourcePermissionModels==null || oldRoleResourcePermissionModels.size()==0) {
						//当原有的list为空，且目前的list不为空
						needAddList.addAll(roleResourcePermissionModels);
					}else {
						for (RoleResourcePermissionModel oldPermissionModel : oldRoleResourcePermissionModels) {
							boolean isdel = true;
							for (RoleResourcePermissionModel roleResourcePermissionModel : roleResourcePermissionModels) {
								if(oldPermissionModel.getResourceid()==roleResourcePermissionModel.getResourceid()) {
									isdel=false;
									break;
								}
							}
							if (isdel) {
								needDeleteList.add(oldPermissionModel);
							}
						}
						
						for (RoleResourcePermissionModel roleResourcePermissionModel : roleResourcePermissionModels) {
							boolean isnew = true;
							for (RoleResourcePermissionModel oldRoleResourcePermissionModel : oldRoleResourcePermissionModels) {
								if(oldRoleResourcePermissionModel.getResourceid()==roleResourcePermissionModel.getResourceid()) {
									roleResourcePermissionModel.setId(oldRoleResourcePermissionModel.getId());
									needUpdateList.add(roleResourcePermissionModel);
									isnew=false;
									break;
								}
							}
							if(isnew) {
								needAddList.add(roleResourcePermissionModel);
							}
						}
					}
				}else {
					//当无资源选中时，所有原有的信息都需删除
					if(oldRoleResourcePermissionModels!=null) {
						needDeleteList.addAll(oldRoleResourcePermissionModels);
					}
				}
			if (needAddList.size()>0) {
				roleResourcePermissionService.save(needAddList);
			}
			if (needUpdateList.size()>0) {
				roleResourcePermissionService.update(needUpdateList);
			}
			if(needDeleteList.size()>0) {
				roleResourcePermissionService.delete(needDeleteList);
			}
			}
		}
		return result;
	}
	
	@RequestMapping("getPermission")
	@ResponseBody
	public Model getPermission(HttpServletRequest request,Model model) {
		int roleid = RequestUtil.getValueByParam(request, "id", 0);
		if(roleid>0) {
			List<RoleResourcePermissionModel> roleResourcePermissionModels = roleResourcePermissionService.findByRoleid(roleid);
			model.addAttribute("permissions",roleResourcePermissionModels);
		}
		return model;
	}

	public RoleResourceService getRoleResourceService() {
		return roleResourceService;
	}

	public void setRoleResourceService(RoleResourceService roleResourceService) {
		this.roleResourceService = roleResourceService;
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public PermissionService getPermissionService() {
		return permissionService;
	}

	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	public RoleResourcePermissionService getRoleResourcePermissionService() {
		return roleResourcePermissionService;
	}

	public void setRoleResourcePermissionService(
			RoleResourcePermissionService roleResourcePermissionService) {
		this.roleResourcePermissionService = roleResourcePermissionService;
	}

}
